local message = require 'jass.message'
local jass = require 'jass.common'
local hook = require 'jass.hook'
local code = require 'jass.code'
local log  = require 'jass.log'

local sc = sc or {}

local StringHash = jass.StringHash
local strHash = {}
--- 获取字符哈希值
sc.getHash = function(str)
    if not strHash[str] then
        strHash[str] = StringHash(str)
    end
    return strHash[str]
end

local TriggerEvaluate = jass.TriggerEvaluate
--- 运行事件触发器
sc.notifyEvent = function(eventName)
    TriggerEvaluate(code.XwNzGetEventTrigger(eventName))
end

--- 是否存在指定事件触发器
sc.hasEvent = function(eventName)
    return code.XwNzHasEventTriggerEx(sc.getHash(eventName))
end

local DisplayTextToPlayer = jass.DisplayTextToPlayer
local DisplayTimedTextToPlayer = jass.DisplayTimedTextToPlayer

local is_custom = false

--拦截一下jass里的函数 增加个开关
function hook.DisplayTextToPlayer(player_handle, x, y, text)
    is_custom = true
    DisplayTextToPlayer(player_handle, x, y, text)
    is_custom = false
end

function hook.DisplayTimedTextToPlayer(player_handle, x, y, time, text)
    is_custom = true
    DisplayTimedTextToPlayer(player_handle, x, y, time, text)
    is_custom = false
end

--返回 false 或者 nil 进行屏蔽  如果不想屏蔽 就返回true
function message.screen_message_hook(info)
    if is_custom then --如果是自定义消息 就不屏蔽 直接返回true
        return true
    end

    --否则 是来自平台发消息

    local name, x, y, text, time, unknow = table.unpack(info)

    local eventName = '异步-拦截平台1250事件'
    if sc.hasEvent(eventName) then
        log.info('原始文本', text)
        text = text:gsub('%[', '【'):gsub('%]', '】'):gsub('%(', '（'):gsub('%)', '）')
        log.info('替换后文本', text)
        local key, int = string.match(text, '服务器存档(.*)保存失败（(%d+)）')
        int = tonumber(int)
        log.info('匹配出来的文本', key, int)
        if key and int and int == 1250 then
            if #key > 3 then
                key = string.sub(key, 1, 3)
            end
            jass.SaveStr(jass.YDHT, sc.getHash(eventName), sc.getHash('拦截Key'), key)
            sc.notifyEvent(eventName)
            jass.RemoveSavedString(jass.YDHT, sc.getHash(eventName), sc.getHash('拦截Key'))
        end
        return false
    end

    --发送一条新的  该接口发送的文本 不会被拦截。
    -- message.screen_message(x, y, "拦截平台文本: " .. text, time, unknow)

    -- return false  --返回 进行屏蔽
end
